package me.trytofeel.dao.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import me.trytofeel.bean.User;
import me.trytofeel.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.ResultSet;
import java.sql.Statement;

/*
 * 根据业务层要求,实现数据查询
 */
public class UserDaoImpl implements UserDao {
    @Override
    public int deleteUserById(int id) {
        // 假设： 因为只有10条数据,所以id范围在1-10才会有删除成功,返回大于1值,否则是0
        return id > 0 && id <= 10 ? 1 : 0; // 模拟受影响的行数
    }

    @Override
    public User selectUserById(int id) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DruidDataSource dataSource = context.getBean(DruidDataSource.class);
        try {
            DruidPooledConnection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from mybatis.student where s_id =" + id);
            if (resultSet.next()) {
                return new User(resultSet.getString("s_name"), resultSet.getString("s_name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
